package org.elephas.webapp.frontend.page.blog;

import org.apache.wicket.Component;
import org.apache.wicket.PageParameters;
import org.apache.wicket.ResourceReference;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.elephas.model.Blog;
import org.elephas.service.ThemeFinder;
import org.elephas.webapp.application.ElephasApplication;
import org.elephas.webapp.component.Theme;
import org.elephas.webapp.frontend.page.BasePage;
import org.elephas.webapp.model.DetachableBlogModel;

public class BlogBasePage extends BasePage implements IHeaderContributor {
    private static final long serialVersionUID = 1L;
    private DetachableBlogModel blogModel;
    @SpringBean
    private ThemeFinder finder;
    public static final String BLOG_NAME = "0";
    public static final String POST_UUID = "1";

    /**
     * Construct.
     *
     * @param params the page parameters
     */
    public BlogBasePage(PageParameters params) {
        super(params);
    }

    public void renderHead(IHeaderResponse response) {
        Theme theme = getTheme();
        ResourceReference css = theme.getCSS(this);
        ResourceReference js = theme.getJavascript(this);
        if(css != null) {
            response.renderCSSReference(css);
        }
        if(js != null) {
            response.renderJavascriptReference(js);
        }
    }

    @Override
    protected void checkParameters(PageParameters params) {
        // there must at least be one parameter denoting the blog
        if(params.isEmpty()) {
            setRedirect(true);
            throw new RestartResponseException(ElephasApplication.get().getHomePage());
        }
    }

    public final Blog getBlog() {
        return getBlogModel().getObject();
    }

    protected Theme getTheme() {
        String theme = getBlog().getConfiguration().getTheme();
        return finder.getTheme(theme);
    }

    public final DetachableBlogModel getBlogModel() {
        if(blogModel == null) {
            blogModel = new DetachableBlogModel(getPageParameters().getString(
                BlogFrontPage.BLOG_NAME));
        }
        return blogModel;
    }

/*
	@Override
	protected Component newHeader(String id) {
		return new Label(id, getBlog().getName()) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onComponentTag(ComponentTag tag) {
				super.onComponentTag(tag);
				tag.setName("h1");
			}
		};
	}

*/
    @Override
    protected Component newHeader(String id) {
        return getTheme().newHeader(id, getBlogModel(), this);
    }

    @Override
    protected Component newFooter(String id) {
        return getTheme().newFooter(id, getBlogModel(), this);
    }
}
